<template>
  <div>
    <el-form ref="searchForm" :model="searchForm" :inline="true">
      <el-form-item>
        <el-input v-model="searchForm.goodsName" placeholder="输入搜索的分类名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getGoodsList()">搜索</el-button>
        <el-button type="primary" @click="dialogFormVisible = true">新建</el-button>

        <el-popconfirm title="确认要删除这些记录吗？" @confirm="delHandler(null)">
          <el-button type="danger" :disabled="delBtnStu" slot="reference">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <!-- 餐品表格 -->
    <el-table :data="tableData" border style="width:100%;margin-bottom: 20px;" :cel1-style="{ padding: '2px' }"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="goodsName" label="餐品名称" width="150"></el-table-column>
      <!-- 如果读取字段数据就是文字，直接显示在表格，那么就使用 prop="字段属性名"-->
      <el-table-column label="餐品图片" width="150">
        <!--数据不是直接显示在页面，而是通过其它模版页面显示 -->
        <template slot-scope="scope">
          <!-- scope表示表格当前行的数据。scope.row就是表格这一行记录(一个分类对象)-->
          <el-image style="width:40px; height:40px" :src="scope.row.goodsCover"/>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格(元)" width="250"></el-table-column>
      <el-table-column prop="description" label="描述" width="250"></el-table-column>
      <el-table-column prop="created" label="创建时间" width="250"></el-table-column>
      <el-table-column prop="updated" label="更新时间" width="250"></el-table-column>
      <el-table-column prop="statu" label="状态" width="150">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.statu == 1" type="success" size="mini">正常</el-tag>
          <el-tag v-else-if="scope.row.statu == 0" type="danger" size="mini">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150px">
        <template slot-scope="scope">
          <el-button type="text" @click="editCategory(scope.row)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm title="确认要删除该记录吗？" @confirm="delHandler(scope.row.goodsId)">
            <el-button type="text" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件
    handleSizeChange()方法，切换一页显示的记录数交互方法。
    -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="current"
                   :page-sizes="[5, 10, 15, 20]" :page-size="size" layout="total,sizes,prev, pager, next,jumper"
                   :total="total">
    </el-pagination>


    <!-- 新建分类消息框-->
    <el-dialog title="餐品信息" width="600px" :visible.sync="dialogFormVisible" @close="closeDialog">
      <el-form :model="goodsForm" ref="goodsForm" :rules="goodsRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上传图片">
              <div style=" border: 1px dashed #000; width:180px; height:180px;">
                <el-upload class="avatar-uploader" name="file" action="/sys/api/upload" :show-file-list="false"
                           :headers="headers" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                  <img v-if="goodsForm.goodsCover" :src="goodsForm.goodsCover" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="餐品名称" prop="goodsName">
              <el-input v-model="goodsForm.goodsName"></el-input>
            </el-form-item>
            <el-form-item label="餐品价格" prop="price">
              <el-input v-model="goodsForm.price"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="餐品种类" prop="categoryId">
              <el-select v-model="goodsForm.categoryId">
                <el-option
                    v-for="(item,index) in categoryDict"
                    :key="index"
                    :value="item.value"
                    :label="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属店铺" prop="businessId">
              <el-select v-model="goodsForm.businessId">
                <el-option
                    v-for="(item,index) in businessDict"
                    :key="index"
                    :value="item.value"
                    :label="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="餐品描述">
          <el-input v-model="goodsForm.description" type="textarea" resize="none">
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="goodsForm.statu">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitCategoryForm('goodsForm')">保存
          </el-button>
          <el-button>重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      dialogFormVisible: false,//新建分类的消息框是否显示 true显示，false不显示
      delBtnStu: true,//批量删除按钮是否可用。true不可用，false可以使用
      //搜索栏的对象
      searchForm: {
        goodsName: ''
      },
      //新建分类对象
      goodsForm: {
        goodsId: '',
        goodsName: '',
        categoryId: '',//种类
        businessId: '',//店铺
        goodsCover: '',//分类图片
        description: '',//描述
        price: '',//价格
        statu: 1,
      },
      tableData: [],//分类信息分页表格数组
      //分页参数
      current: 1,
      size: 5,
      total: 0,
      //消息框 添加分类表单验证
      goodsRules: {
        goodsName: [
          {required: true, message: '餐品名称不能为空', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '餐品价格不能为空', trigger: 'blur'},
        ],
        categoryId: [
          {required: true, message: '餐品种类不能为空', trigger: 'change'}
        ],
        businessId: [
          {required: true, message: '所属店铺不能为空', trigger: 'change'}
        ]
      },
      //表格复选框选中数组，存储选中表格中某些行对象
      selection: [],
      headers: {
        token: JSON.parse(localStorage.getItem('TOKEN'))
      },
      categoryDict: [],
      businessDict: [],
    }
  },
  created() {
    this.getGoodsList();
    this.getDict();
  },
  methods: {
    //重置categoryForm对象的方法
    resetGoodsForm() {
      this.goodsForm = {
        goodsName: '',
        categoryId: '',//种类
        businessId: '',//店铺
        goodsCover: '',//分类图片
        description: '',//描述
        price: '',//价格
        statu: 1,
      }
    },
    //关闭对话框重置businessForm表单对象
    closeDialog() {
      this.resetGoodsForm();
    },
    //编辑分类数据
    editCategory(row) {
      //请求服务器端，通过categoryId查询该商家对象，然后将获得商家详细数据 回显到对话框
      Object.assign(this.goodsForm, row)
      this.dialogFormVisible = true;
      let url = "/goods/getDictById/" + row.goodsId;
      this.$axios.get(url).then(response => {
        this.goodsForm.categoryId=String(response.data.resultdata.categoryId)
        this.goodsForm.businessId=String(response.data.resultdata.businessId)
        console.log(this.goodsForm)
      }).catch(e => {
        console.log(e);
      })
    },
    handleSelectionChange(arr) {//选择表格的复选框触发事件，参数arr就是选中
      this.selection = arr;
      if (this.selection) {
        this.delBtnStu = (this.selection.length == 0)
      }
    },
    delHandler(categoryId) { //删除记录的方法
      //请求服务器端，传递需要删除 分类信息id的数组
      var categoryIds = []; //删除分类编号数组
      categoryId ? categoryIds.push(categoryId) : this.selection.forEach(category => {
        categoryIds.push(category.categoryId);
      });
      let url = "/goods/delete";
      this.$axios.post(url, categoryIds).then(response => {
        this.$message({
          message: response.data.resultdata,
          type: "success"
        });
        //重新加载 分类信息表格数据
        this.getGoodsList();
      }).catch(e => {
        console.log(e);
      });
    },
    submitCategoryForm(formName) { //提交服务器端进行保存分类
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('/goods/' +
              (this.goodsForm.goodsId ? 'update' : 'save'), this.goodsForm)
              .then(response => {
                this.$message({
                  showClose: true,
                  message: response.data.resultdata,
                  type: 'success',
                });
                this.getGoodsList(); //录入新的餐品数据，重新加载表格数据
                this.dialogFormVisible = false; //保存成功，录入消息框隐藏
                this.resetGoodsForm(); //重置categoryForm表单对象
              }).catch(e => {
            console.log(e);
          })
        } else {
          return false;
        }
      });
    },
    beforeAvatarUpload() { //上传之前进行操作
      //对于上传图片有限制：图片格式jpeg 图片大小 10MB
    },
    handleAvatarSuccess(response, file) { //上传图片成功之后的回调。
      //图片上传，获得上传图片的地址（图片数据）进行回显。
      //参数response就是服务器端返回Result对象，不需要像axios对象中的操作response.data这样。
      this.goodsForm.goodsCover = response.resultdata
    },
    handleCurrentChange(val) {//切换到某一页数据 参数val 就是切换页码
      this.current = val;
      //页码发生变化，重新去请求Table中分页数据
      this.getGoodsList();
    },
    handleSizeChange(val) { //一页显示的记录数切换，参数val 切换一页要显示的数量
      this.size = val
      //一页显示的记录数发生变化，重新去请求Table中分页数据
      this.getGoodsList();
    },
    getGoodsList() { //加载页面上分类数据
      //Vue2中，将axios已经挂载this（vue实例中）
      let url = "/goods/list";
      this.$axios.get(url, {
        params: {
          //搜索的内容
          goodsName: this.searchForm.goodsName,
          current: this.current,
          size: this.size
        }
      }).then(response => {
        //服务器返回分页对象数据。具体分类数据records属性中。
        this.tableData = response.data.resultdata.records;
        this.current = response.data.resultdata.current;
        this.size = response.data.resultdata.size;
        this.total = response.data.resultdata.total;
      }).catch(e => {
        console.log(e);
      })
    },
    getDict() {
      this.$axios.get('/goods/dict').then(response => {
        this.categoryDict = response.data.resultdata.categoryList;
        this.businessDict = response.data.resultdata.businessList;
      })
    }
  },
}
</script>
<style scoped>
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
}
</style>
